//
//  XZSelectStudentVC.m
//  优学荟管理系统
//
//  Created by edz on 2018/1/22.
//  Copyright © 2018年 星道三好. All rights reserved.
//

#import "XZSelectStudentVC.h"
#import "XZSelectCell.h"
#import "HNAssignmentVC.h"

@interface XZSelectStudentVC ()<UITableViewDataSource, UITableViewDelegate>

/** 表单 */
@property (nonatomic, strong) UITableView *tableView;
/** 数据存放地 */
@property (nonatomic, strong) NSMutableArray *DataArr;
/** 当前的页 */
@property (nonatomic, assign) NSInteger CurrentPage;
/** 临时保存的页数 */
@property (nonatomic, assign) NSInteger TempPage;

/** 头部试图 */
@property (nonatomic, strong) UIView *headerView;

@end

@implementation XZSelectStudentVC {
    UIButton *_selectedBtn;
    int stundentNum;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"选择学生";
    
    [self ConfigtableView];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(leftBarButtonItemAction) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
}



-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}]; //设置标题颜色
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    
    [SVProgressHUD dismiss];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];//设置标题颜色
}

- (void)leftBarButtonItemAction{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Config
/** 配置tableView */
- (void)ConfigtableView {
    
    self.view.backgroundColor = ColorRGB(245, 245, 245);
    // 设置代理
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 设置占位View
    self.tableView.tableFooterView = [UIView new];
    // 设置头部试图
    self.tableView.tableHeaderView = self.headerView;
    // 设置自动Cell高
    self.tableView.rowHeight = 55;
    // 设置预注册
    [self.tableView registerClass:[XZSelectCell class] forCellReuseIdentifier:@"cell"];
    // 增加刷新头
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 每次下拉刷新时都保存好当前的页数，预防刷新失败后页数错乱
        self.TempPage = self.CurrentPage;
        // 当前的刷新设为1
        self.CurrentPage = 1;
        // 获取数据
        [self RefreshData];
    }];
    // 增加刷新尾
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 获取数据
        [self RefreshData];
    }];
    // 开始刷新
    [self.tableView.mj_header beginRefreshing];
}


#pragma mark - 网络
- (void)RefreshData {
    
    //   NSString *url = [NSString stringWithFormat:@"yxhUser.do?action=bindStudentsDetial&search=%@&pageNumber=%ld",self.searchStr.length != 0 ? self.searchStr:@"",(long)self.page];
    
    NSDictionary *Params = @{
                             @"action":@"bindStudentsDetial",
                             @"pageNumber":@(self.CurrentPage),
                             @"search":@""
                             };
    
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
        // 结束刷新
        [self MgrRefresh:1];
        // 数据处理
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            // 拿到数据
            NSArray *Arr = Obj[@"t"][@"dataList"];
            // 如果当前的页码是1就先清空原数据
            self.CurrentPage == 1 ? [self.DataArr removeAllObjects] : nil;
            // 如果没有数据就提示没数据了
            if (Arr.count == 0) {
                [self MgrRefresh:2];
            } else {
                // 终于有数据啦
                [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    // 处理模型转对象
                    ZYstudentDetailModel *model = [ZYstudentDetailModel new];
                    [model setValuesForKeysWithDictionary:obj];
                    [self.DataArr addObject:model];
                    
                }];
                self.CurrentPage += 1;
                [self MgrRefresh:3];
            }
        } else {
            // 数据获取失败
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
            [self MgrPage];
        }
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
        [self MgrRefresh:1];
        [self MgrPage];
    }];
}

/** 刷新失败时的页数处理 */
- (void)MgrPage {
    
    self.CurrentPage = self.TempPage;
}

/** 刷新状态 1结束刷新 2没有更多数据了 3刷新表单*/
- (void)MgrRefresh:(NSInteger)State {
    
    if (State == 1) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } else if (State == 2) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else if (State == 3) {
        [self.tableView reloadData];
    } else  {
        // 无
    }
}

#pragma mark - tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XZSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.model = self.DataArr[indexPath.row];
    cell.CallBack = ^() {
        // 每次进来先设置为0 再进行累加
        stundentNum = 0;
        [self.DataArr enumerateObjectsUsingBlock:^(ZYstudentDetailModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.seleted == YES) {
                stundentNum += 1;
            }
        }];
        NSString *str = [NSString stringWithFormat:@"   已选中 %d人",stundentNum];
        [_selectedBtn setTitle:str forState:(UIControlStateNormal)];
    };
    return cell;
}

#pragma mark - Get
- (NSMutableArray *)DataArr {
    if (!_DataArr) {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 130) style:(UITableViewStylePlain)];
        _tableView.backgroundColor = ColorRGB(245, 245, 245);
        [self.view addSubview:_tableView];
        /// 底部按钮
        UIButton *bottomBtn = [[UIButton alloc] initWithFrame:CGRectMake(18, _tableView.height + 10, SCREEN_WIDTH - 36, 45)];
        bottomBtn.backgroundColor = RGBColor(42, 197, 127);
        bottomBtn.layer.cornerRadius = 5;
        bottomBtn.layer.masksToBounds = YES;
        [bottomBtn setTitle:@"确认" forState:(UIControlStateNormal)];
        [bottomBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [bottomBtn addTarget:self action:@selector(Sendclick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:bottomBtn];
    }
    return _tableView;
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
        
        UIView *backRandView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60-15)];
        backRandView.backgroundColor = [UIColor whiteColor];
        [self.headerView addSubview:backRandView];
        ///一以选中按钮
        _selectedBtn = [[UIButton alloc] initWithFrame:CGRectMake(25, 15, 150, 44)];
        [_selectedBtn setImage:[UIImage imageNamed:@"icon_choice"] forState:(UIControlStateNormal)];
        [_selectedBtn setTitle:@"   已选中 0人" forState:(UIControlStateNormal)];
        _selectedBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_selectedBtn setTitleColor:ColorRGB(102, 102, 102) forState:(UIControlStateNormal)];
        ///计算文字宽度
        CGSize titleSize = [_selectedBtn.currentTitle sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:_selectedBtn.titleLabel.font.fontName size:_selectedBtn.titleLabel.font.pointSize]}];
        titleSize.height = 20;
        titleSize.width += 35;
        CGRect frame = _selectedBtn.frame;
        frame.size = titleSize;
        _selectedBtn.frame = frame;
        [backRandView addSubview:_selectedBtn];
        
        ///全选按钮
        UIButton *allBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 80, 15, 60, 20)];
        [allBtn setTitle:@"全选" forState:(UIControlStateNormal)];
        allBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [allBtn setTitleColor:ColorRGB(102, 102, 102) forState:(UIControlStateNormal)];
        [allBtn addTarget:self action:@selector(allSeleted:) forControlEvents:(UIControlEventTouchUpInside)];
        [backRandView addSubview:allBtn];
        
    }
    return _headerView;
}

#pragma mark - 点击把选中学生的id 打包传到下个页面
- (void)Sendclick {
    
    NSMutableArray *studens = @[].mutableCopy;
    ///拿到最新的model 看哪个被选中 则添加进数组
    [self.DataArr enumerateObjectsUsingBlock:^(ZYstudentDetailModel  *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.seleted == YES) {
            [studens addObject:obj.uid];
        }
    }];

    HNAssignmentVC *vc = [HNAssignmentVC new];
    vc.type = HNAssignmentTypeNotice;
    vc.Uids = [studens componentsJoinedByString:@","];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 全选
- (void)allSeleted:(UIButton *)sender {
    //默认是不选中状态 然后根据状态改变值
    if (sender.selected == YES) {
        sender.selected = NO;
        [sender setTitle:@"全选" forState:UIControlStateNormal];
    } else {
        sender.selected = YES;
        [sender setTitle:@"取消全选" forState:UIControlStateNormal];
    }
    
    ///一进来清空变量的值，循环便利累加值 再进行赋值到按钮
    stundentNum = 0;
    [self.DataArr enumerateObjectsUsingBlock:^(ZYstudentDetailModel  *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.seleted = sender.selected;
        if (obj.seleted == YES) {
            stundentNum += 1;
        }
    }];
    NSString *str = [NSString stringWithFormat:@"   已选中 %d人",stundentNum];
    [_selectedBtn setTitle:str forState:(UIControlStateNormal)];
    [self.tableView reloadData];
}


@end
